//
//  DockManager.m
//  McRemote
//
//  Created by Magic on 2/12/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "DockManager.h"
#import "FileManager.h"
#import "MRMessageCenter.h"

@implementation DockManager {
    
    NSMutableArray *_dockAppNames;
    NSMutableArray *_launchedAppNames;
    //NSMutableDictionary *_dockAppIcons;
}

@synthesize activeApplicationName;

+ (DockManager *)sharedManager
{
    static DockManager *sharedManager;
    static dispatch_once_t token;
    dispatch_once(&token, ^{
        sharedManager = [[DockManager alloc] init];
    });
    
    return sharedManager;
}

- (id)init {
    self = [super init];
    if (self) {
        _dockAppNames = [NSMutableArray arrayWithCapacity:10];
        _launchedAppNames = [NSMutableArray arrayWithCapacity:6];
    }
    return self;
}

- (void)clearDock
{
    [_dockAppNames removeAllObjects];
    [_launchedAppNames removeAllObjects];
}

- (void)addDockAppWithName:(NSString *)name
{
    if (![_dockAppNames containsObject:name]) {
        [_dockAppNames addObject:name];
    }
    
}

- (void)addLaunchedAppWithName:(NSString *)name
{
    if (![_launchedAppNames containsObject:name] && ![_dockAppNames containsObject:name]) {
        
        [_launchedAppNames addObject:name];
    }    
}

- (void)terminateAppWithName:(NSString *)name
{
    if ([_launchedAppNames containsObject:name]) {
        [_launchedAppNames removeObject:name];
    } 
}

- (void)setDockAppIconData:(NSData *)data forName:(NSString *)name
{
    //write to document directory
    [[FileManager sharedManager] writeToDocument:data fileName:name extension:@"png"];
    
    //UIImage *appIcon = [UIImage imageWithData:data];
    
    //[_dockAppIcons setObject:appIcon forKey:name];
    

    //[[NSNotificationCenter defaultCenter] postNotificationName:@"NewDockAppIcon" object:nil userInfo:[NSDictionary dictionaryWithObjectsAndKeys:name,@"name",appIcon,@"icon", nil]];
}

- (NSUInteger)numberOfDockApp
{
    NSUInteger count = [_dockAppNames count] + [_launchedAppNames count];
    
    
    if (count == 0) {
        //[[MRMessageCenter sharedCenter] sendNeedDockInfo];
    }    
    
    return count;
}

- (NSString *)appNameAtIndex:(NSUInteger)index
{
    NSUInteger dockAppCount = [_dockAppNames count];
    if (index >= dockAppCount) {
        return [_launchedAppNames objectAtIndex:index-dockAppCount];
    }
    return [_dockAppNames objectAtIndex:index];
}

- (NSString *)dockAppNameAtIndex:(NSUInteger)index
{
    return [self appNameAtIndex:index];
}

- (UIImage *)dockAppIconAtIndex:(NSUInteger)index
{
    NSString *appName = [self appNameAtIndex:index];
    UIImage *image;// = [_dockAppIcons objectForKey:appName];
    //if (image == nil) {
    image = [[FileManager sharedManager] imageNamed:appName];
    //}
    if (image == nil) {
        [[MRMessageCenter sharedCenter] sendNeedDockIconWithName:appName];
    }
    
    return image;
}

@end
